/**
 *
 */
package com.ltwc.lttv.net;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.content.Context;
import android.os.PowerManager;
import android.text.TextUtils;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 辅助工具类
 *
 * @author hongming.wang
 * 创建时间： 2015年11月24日 上午11:46:50
 * 项目名称： AMapLocationDemo2.x
 * 文件名称: Utils.java
 * 类型名称: Utils
 */
public class Utils {

    private static SimpleDateFormat sdf = null;

    public synchronized static String formatUTC(long l, String strPattern) {
        if (TextUtils.isEmpty(strPattern)) {
            strPattern = "yyyy-MM-dd HH:mm:ss";
        }
        if (sdf == null) {
            try {
                sdf = new SimpleDateFormat(strPattern, Locale.CHINA);
            } catch (Throwable e) {
            }
        } else {
            sdf.applyPattern(strPattern);
        }
        return sdf == null ? "NULL" : sdf.format(l);
    }

    public static boolean isNull(Object obj) {
        if (obj == null)
            return true;

        if (obj instanceof CharSequence)
            return ((CharSequence) obj).length() == 0;

        if (obj instanceof Collection)
            return ((Collection) obj).isEmpty();

        if (obj instanceof Map)
            return ((Map) obj).isEmpty();

        if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isNull(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }
        return false;
    }

    public static boolean notNull(Object obj) {
        return !isNull(obj);
    }

    public static boolean isJsonString(String str) {
        boolean isJsonStr;
        try {
            JSONObject jsonObject = new JSONObject(str);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            isJsonStr = false;
        }
        try {
            JSONArray jsonArray = new JSONArray(str);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            isJsonStr = false;
        }
        return isJsonStr;
    }

    /**
     * 将json格式的字符串解析成Map对象 <li>
     * json格式：{"name":"admin","retries":"3fff","testname"
     * :"ddd","testretries":"fffffffff"}
     */
    public static <T> HashMap<String, T> jsonToMap(String json) {
        // 将json字符串转换成jsonObject
        JSONObject jsonObject = null;
        HashMap<String, T> hashMap = new HashMap<>();
        try {
            jsonObject = new JSONObject(json);
            Iterator it = jsonObject.keys();
            // 遍历jsonObject数据，添加到Map对象
            String key;
            Object value;
            while (it.hasNext()) {
                key = String.valueOf(it.next());
                value = jsonObject.get(key);
                if (isNull(hashMap)) {
                    hashMap = new HashMap<>();
                }
                hashMap.put(key, (T) value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return hashMap;
    }

    /**
     * 将Map转换成Json
     *
     * @param jsonMap
     * @return
     * @throws Exception
     */
    public static String mapToJson(Map<String, Object> jsonMap) throws Exception {
        StringBuilder result = new StringBuilder();
        result.append("{");
        Iterator<Map.Entry<String, Object>> entryIterator = jsonMap.entrySet().iterator();
        for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof Map) {
                System.out.println("\n Object Key : " + key);
                String mapJson = mapToJson((Map<String, Object>) value);
                result.append("\"").append(key).append("\":").append(mapJson);
            } else {
                Gson gson = new Gson();
                String json = gson.toJson(value);
                result.append("\"").append(key).append("\":").append(json);
            }
            // 最后一个去掉 逗号
            entryIterator.next();
            if (entryIterator.hasNext()) {
                result.append(",");
            }
        }
        result.append("}");
        return result.toString();
    }

    public static String unicodeToChinese(String dataStr) {
        final StringBuilder buffer = new StringBuilder();
        Pattern p = Pattern.compile("\\\\u([\\S]{4})([^\\\\]*)");
        Matcher match = p.matcher(dataStr);
        if (match.find()) {
            while (match.find()) {
                char letter = (char) Integer.parseInt(match.group(1), 16);
                buffer.append(Character.toString(letter));
                buffer.append(match.group(2));
            }
        } else {
            buffer.append(dataStr);
        }

        return buffer.toString();
    }

    /**
     * 定义script的正则表达式
     */
    private static final String REGEX_SCRIPT = "<script[^>]*?>[\\s\\S]*?<\\/script>";
    /**
     * 定义style的正则表达式
     */
    private static final String REGEX_STYLE = "<style[^>]*?>[\\s\\S]*?<\\/style>";
    /**
     * 定义HTML标签的正则表达式
     */
    private static final String REGEX_HTML = "<[^>]+>";
    /**
     * 定义空格回车换行符
     */
    private static final String REGEX_SPACE = "\\s*|\t|\r|\n";
    public static String formatHtmStr(String htmlStr) {
        // 过滤script标签
        Pattern p_script = Pattern.compile(REGEX_SCRIPT, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll("");
        // 过滤style标签
        Pattern p_style = Pattern.compile(REGEX_STYLE, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll("");
        // 过滤html标签
        Pattern p_html = Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll("");
        // 过滤空格回车标签
        Pattern p_space = Pattern.compile(REGEX_SPACE, Pattern.CASE_INSENSITIVE);
        Matcher m_space = p_space.matcher(htmlStr);
        htmlStr = m_space.replaceAll("");
        return htmlStr.trim(); // 返回文本字符串
    }
    @SuppressLint("WakelockTimeout")
    public static void wakeUpAndUnlock(Context context){
        //屏锁管理器
        KeyguardManager km= (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
        //解锁
        kl.disableKeyguard();
        //获取电源管理器对象
        PowerManager pm=(PowerManager) context.getSystemService(Context.POWER_SERVICE);
        //获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
        @SuppressLint("InvalidWakeLockTag")
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");
        //点亮屏幕
        wl.acquire();
        //释放
        wl.release();
    }
}
